import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core'
import { ActivatedRoute, Router } from '@angular/router'
import { NzMessageService } from 'ng-zorro-antd'

import { PageService } from '@shared/services/page.service'
import { ETabScrollStatus } from '@shared/enums'
import { CommonAcquirerService } from '@shared/services/acquirer.service'
import {
  ExchangeRate,
  IUpdateAcquirerTradeInfo,
  TradeInfo,
  Access,
  AccessMode,
  MerchantFeature,
  IUpdateAcquirerFeature,
  Acquirer,
} from '@shared/interfaces/acquirer'
import { DetailTabClass } from '@shared/classes/DetailTabClass'
import { numScale, parseSelRate } from 'app/utils/helpers'
import { AcquirerService } from '../../acquirer.service'
import { I18NService } from '@core'

@Component({
  selector: 'app-acquirer-detail-tab-trades',
  templateUrl: './tab-trades.component.html',
  styleUrls: ['./tab-trades.component.less'],
})
export class AcquirerDetailTabTradesComponent extends DetailTabClass<TradeInfo> implements OnInit {
  @ViewChild('curOperate') curOperate: TemplateRef<void>
  @ViewChild('insOperate') insOperate: TemplateRef<void>
  @ViewChild('merOperate') merOperate: TemplateRef<void>

  @ViewChild('tpMultiCurrSupport') tpMultiCurrSupport: TemplateRef<void>
  @ViewChild('tpIsSupportRisk') tpIsSupportRisk: TemplateRef<void>
  @ViewChild('tpIsSupportPostRisk') tpIsSupportPostRisk: TemplateRef<void>

  // 这个fields在这里是'交易币种转换'和'机构密钥配置'.
  fields = {
    Currency: '1', // Trade Currency
    Institution: '2', // Ins Access Key
    MerchantFunc: '3', // Merchant Function
  }
  buyRateOptions = [] // 转换汇率选项
  params: IUpdateAcquirerTradeInfo = {
    version: 0,
    trade: null,
  }
  merchantFeature: MerchantFeature // 商户功能配置

  constructor(
    public pageService: PageService,
    public route: ActivatedRoute,
    private router: Router,
    private commonAcquirerService: CommonAcquirerService,
    private acquirerService: AcquirerService,
    private messageService: NzMessageService,
    private i18n: I18NService,
  ) {
    super(pageService, route)
  }

  ngOnInit() {
    this.initialData()
  }

  initialData() {
    this.commonAcquirerService.viewAcquirer$.value$.subscribe(acquirer => {
      // Reset columns
      this.initialColumns()

      this.params.version = acquirer.institution.version
      this.data = acquirer.institution.common.tradeInfo

      /** 渲染币种 */
      this.renderCurrency()

      /** 渲染机构密钥 */
      this.renderIns()

      /** 渲染商户功能配置 */
      this.renderMerchantFeature(acquirer)

      // 完成后台数据安排后 再把每个数据的column设置一个id 来控制编辑状态
      this.setupIdForColumn(this.fields)
    })
    this.pageService.setTabScrollStatus(ETabScrollStatus.Scroll)
  }

  renderCurrency(): void {
    this.setEdit(this.fields.Currency, !!this.data.exchangeRates ? this.data.exchangeRates.length : 0)
    this.setupCurrencyColumns(this.data.exchangeRates)
  }

  renderIns(): void {
    this.setEdit(this.fields.Institution, !!this.data.access ? this.data.access.length : 0)
    this.setupInsColumns(this.data.access)
  }

  renderMerchantFeature(acquirer: Acquirer): void {
    this.merchantFeature = acquirer.institution.common.feature
    this.merchantFeature.multiTransCurrConfig = this.merchantFeature.multiTransCurrConfig || false
    this.setEdit(this.fields.MerchantFunc, !!this.merchantFeature ? Object.keys(this.merchantFeature).length : 0)
    this.setupMerColumns(this.merchantFeature)
  }

  setupCurrencyColumns(exchangeRates: ExchangeRate[]): void {
    if (!exchangeRates || exchangeRates.length <= 0) {
      return
    }

    for (const exchange of exchangeRates) {
      this.columns[this.fields.Currency].push([
        {
          span: 5,
          label: 'BIZ.ACQUIRER.OTHER.TRADE.MERCHANT_CURRENCY',
          labelI18n: 'BIZ.ACQUIRER.OTHER.TRADE.MERCHANT_CURRENCY',
          index: 'srcCurrency',
          value: exchange.srcCurrency,
        },
        {
          span: 5,
          label: 'BIZ.ACQUIRER.OTHER.TRADE.CHANNEL_CURRENCY',
          labelI18n: 'BIZ.ACQUIRER.OTHER.TRADE.CHANNEL_CURRENCY',
          index: 'dstCurrency',
          value: exchange.dstCurrency,
        },
        {
          span: 5,
          label: 'BIZ.ACQUIRER.OTHER.TRADE.CONVERT_RATE',
          labelI18n: 'BIZ.ACQUIRER.OTHER.TRADE.CONVERT_RATE',
          index: 'selRate',
          value: parseSelRate(exchange.selRate),
        },
        {
          span: 5,
          label: 'Mark Up',
          index: 'markup',
          value: `${numScale(exchange.markup, 2)}%`,
        },
        {
          span: 4,
          label: 'GENERAL.INFO.OPERATION',
          labelI18n: 'GENERAL.INFO.OPERATION',
          template: this.curOperate,
          operate: true,
          acl: ['api.put.camel.institution.one.trade'],
        },
      ])
    }
  }

  setupInsColumns(accesses: Access[] = []): void {
    const merAccess = accesses.find(access => access.mode === AccessMode.Merchant)
    const acquirerAccess = accesses.find(access => access.mode === AccessMode.Acquirer)
    const nodeAccess = accesses.find(access => access.mode === AccessMode.Node)
    this.columns[this.fields.Institution].push([
      {
        span: 4,
        label: 'BIZ.ACQUIRER.OTHER.TRADE.MERCHANT_ACCESS',
        labelI18n: 'BIZ.ACQUIRER.OTHER.TRADE.MERCHANT_ACCESS',
        value: this.renderYesOrNot(!!merAccess),
      },
      {
        span: 8,
        label: 'BIZ.ACQUIRER.OTHER.TRADE.ACQUIRER_ACCESS',
        labelI18n: 'BIZ.ACQUIRER.OTHER.TRADE.ACQUIRER_ACCESS',
        value: (acquirerAccess && acquirerAccess.key) || this.trans('GENERAL.INFO.SWITCH.OFF'),
      },
      {
        span: 8,
        label: 'BIZ.ACQUIRER.OTHER.TRADE.NODE_ACCESS',
        labelI18n: 'BIZ.ACQUIRER.OTHER.TRADE.NODE_ACCESS',
        value: (nodeAccess && nodeAccess.key) || this.trans('GENERAL.INFO.SWITCH.OFF'),
      },
      {
        span: 4,
        label: 'GENERAL.INFO.OPERATION',
        labelI18n: 'GENERAL.INFO.OPERATION',
        template: this.insOperate,
        operate: true,
        acl: ['api.put.camel.institution.one.trade'],
      },
    ])
  }

  setupMerColumns(merchantFeature: MerchantFeature): void {
    const { multiTransCurrConfig, isSupportRisk, isSupportPostRisk } = merchantFeature
    this.columns[this.fields.MerchantFunc] = [
      [
        /** 按需求隐藏多币种 */
        // {
        //   span: 10,
        //   label: 'BIZ.ACQUIRER.OTHER.TRADE.MULTI_CURRENCIES_SUPPORTED',
        //   labelI18n: 'BIZ.ACQUIRER.OTHER.TRADE.MULTI_CURRENCIES_SUPPORTED',
        //   value: merchantFeature.multiTransCurrConfig,
        //   displayValue: this.renderYesOrNot(multiTransCurrConfig),
        //   template: this.tpMultiCurrSupport,
        // },
        // {
        //   span: 10,
        //   label: '是否支持事中风控',
        //   labelI18n: 'BIZ.ACQUIRER.OTHER.TRADE.RISK_CONTROL_SUPPORTED',
        //   value: merchantFeature.isSupportRisk,
        //   displayValue: this.renderYesOrNot(isSupportRisk),
        //   template: this.tpIsSupportRisk,
        // },
        {
          span: 20,
          label: '是否支持事后风控',
          labelI18n: 'BIZ.ACQUIRER.OTHER.TRADE.POST_RISK_CONTROL_SUPPORTED',
          value: merchantFeature.isSupportPostRisk,
          displayValue: this.renderYesOrNot(isSupportPostRisk),
          template: this.tpIsSupportPostRisk,
        },
        {
          span: 4,
          label: 'GENERAL.INFO.OPERATION',
          labelI18n: 'GENERAL.INFO.OPERATION',
          template: this.merOperate,
          operate: true,
          acl: ['api.put.camel.institution.one.trade'],
        },
      ],
    ]
  }

  renderYesOrNot(value: boolean): string {
    return value ? this.trans('GENERAL.INFO.YES') : this.trans('GENERAL.INFO.NO')
  }

  switchMultiCurrSupport(value): void {
    this.merchantFeature.multiTransCurrConfig = value
  }

  switchIsSupportRisk(value): void {
    this.merchantFeature.isSupportRisk = value
  }

  switchIsSupportPostRisk(value): void {
    this.merchantFeature.isSupportPostRisk = value
  }

  // abstract methods
  onCancel() {
    // If user cancel the edit, the value should retain as initial value.
    this.columns[this.field][this.rowIndex].forEach(column => {
      if (!column.index) return
      column.value = this.data.exchangeRates[this.rowIndex][column.index]
    })
  }

  onSubmit() {
    try {
      if (this.field === '3') {
        this.submitFeature()
        return
      }
      this.columns[this.field][this.rowIndex].forEach(column => {
        if (!column.index) return
        if (column.index === 'markup') {
          this.data.exchangeRates[this.rowIndex][column.index] = Number(column.value)
          column.displayValue = `${column.value}%`
        } else {
          this.data.exchangeRates[this.rowIndex][column.index] = column.value
        }
      })
      this.params.trade = this.data
      this.acquirerService.updateTradeInfoOfAcquirer(this.params, this.getID()).subscribe(acquirer => {
        this.commonAcquirerService.setViewingAcquirer(acquirer)
      })
      this.messageService.success(this.trans('GENERAL.NOTIFICATION.UPDATE_SUCCESS'))
    } catch (error) {
      this.messageService.error(this.trans('GENERAL.NOTIFICATION.UPDATE_FAIL'))
    }
    // Pending SiKin to confirm this with backend
    // "access": [
    //   {
    //     "mode": 0,
    //     "key": "string"
    //   }
    // ]
    // this.acquirerService.updateAuditOfAcquirer()
  }

  /** update feature */
  submitFeature() {
    const reqData: IUpdateAcquirerFeature = {
      feature: this.merchantFeature,
      version: this.params.version,
    }
    this.acquirerService.updateFeaturesOfAcquirer(reqData, this.getID()).subscribe(
      (acquirer) => {
        this.commonAcquirerService.setViewingAcquirer(acquirer)
        this.renderMerchantFeature(acquirer)
        this.messageService.success(this.trans('GENERAL.NOTIFICATION.UPDATE_SUCCESS'))
      },
      (err) => {
        this.messageService.error(this.trans('GENERAL.NOTIFICATION.UPDATE_FAIL'))
      }
    )
  }

  goEditTrade(): void {
    this.router.navigate(['./edit'], { relativeTo: this.route })
  }

  initialColumns() {
    /*
     * 这个columns是用来收集所有需要display在这个tab里面的数据.
     * 比如 "交易币种转换" = '1', 然后交易币种转换里有一个Array = [商户交易币种, 转换交易币种, 转换汇率, 等等] 然后他在columns里就是
     * {'1': [[{商户交易币种, 转换交易币种, 转换汇率, 等等}]]}
     */
    // 现在这个trades component需要展示2个field. 这里创建2个空的Array在this.columns里的field
    for (const key in this.fields) {
      this.columns[this.fields[key]] = []
    }
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }
}
